package edu.metrostate.capstonediner;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Scanner;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.util.Log;

public final class DatabaseHTTP {
	private static final String HIGH_SCORE_URL = "http://www.kruegs.net/CapstoneDiner/view_score.php";
	private static final String INSERT_USER_URL = "http://www.kruegs.net/CapstoneDiner/insert_user.php";
	private static final String INSERT_SCORE_URL = "http://www.kruegs.net/CapstoneDiner/insert_score.php";
	private static final String VALIDATE_USER_URL = "http://www.kruegs.net/CapstoneDiner/validate_user.php";
	private static final String APP_STORE_URL = "http://www.kruegs.net/CapstoneDiner/view_appstore.php";
	private static final String INSERT_PAYMENT_URL = "http://www.kruegs.net/CapstoneDiner/insert_payment.php";
	private static final String INSERT_PURCHASE_URL = "http://www.kruegs.net/CapstoneDiner/insert_purchase.php";
	private static final String VERIFY_PAYMENT_URL = "http://www.kruegs.net/CapstoneDiner/verify_payment.php";
	private static final String VERIFY_PURCHASE_URL = "http://www.kruegs.net/CapstoneDiner/verify_purchase.php";;
	
	public static ArrayList<String> getHighScoreList() {
		final int LINE_SIZE = 22;
		
		ArrayList<String> result = new ArrayList<String>(10);
		InputStream myStream = null;
		Scanner input;
		String playerName;
		String score;
		int count = 0;
		
		try {
			myStream = getStream(HIGH_SCORE_URL);
			input = new Scanner(myStream);
			input.useDelimiter("\\|");
			
			while (input.hasNext() && count < Constants.NUMBER_HIGH_SCORE_DISPLAYED) {
				playerName = input.next().trim();
				if (input.hasNextInt()) {
					score = Integer.toString(input.nextInt());
					result.add(playerName + spaces(LINE_SIZE - playerName.length() - score.length()) + score);
				}
				
				count++;
			}
			
		} catch (IOException e) {
			return new ArrayList<String>();
		} finally {
			if (myStream != null) {
				try {
					myStream.close();
				} catch (IOException e) {
					
				}
			}
		}
		
		return result;
	}
	
	private static String spaces(int length) {
		if (length < 1) {
			return "";
		}
		
		char[] charSpaces = new char[length];
		
		for (int i = 0; i < length; i++) {
			charSpaces[i] = ' ';
		}
		
		return new String(charSpaces);
	}
	
	public static void SaveScore(String user, int score) {
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("login_ID", user));
		params.add(new BasicNameValuePair("high_score", Integer.toString(score)));
		
		sendPost(INSERT_SCORE_URL, params);
	}
	
	public static boolean SaveUser(String user, String password, String firstName, String lastName) {
		boolean isSuccess;
		
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("login_ID", user));
		params.add(new BasicNameValuePair("password", password));
		params.add(new BasicNameValuePair("first_name", firstName));
		params.add(new BasicNameValuePair("last_name", lastName));
		
		isSuccess = sendPost(INSERT_USER_URL, params);
		
		return isSuccess;
	}
	
	public static boolean ValidateUser(String user, String password) {
		boolean isSuccess;
		
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("login_ID", user));
		params.add(new BasicNameValuePair("password", password));
		
		isSuccess = sendPost(VALIDATE_USER_URL, params);
		
		return isSuccess;
	}
	
	public static boolean VerifyPaymentSetup(String user) {
		boolean isSuccess;
		
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("login_ID", user));
		
		isSuccess = sendPost(VERIFY_PAYMENT_URL, params);
		
		return isSuccess;
	}
	
	public static boolean VerifyPurchase(String user, String itemID) {
		boolean isSuccess;
		
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("login_ID", user));
		params.add(new BasicNameValuePair("item_ID", itemID));
		
		isSuccess = sendPost(VERIFY_PURCHASE_URL, params);
		
		return isSuccess;
	}
	
	public static ArrayList<String> getAppStoreList() {
		final int LINE_SIZE = 22;
		
		ArrayList<String> result = new ArrayList<String>(10);
		InputStream myStream = null;
		Scanner input;
		String itemID;
		String appName;
		String price;
		
		try {
			myStream = getStream(APP_STORE_URL);
			input = new Scanner(myStream);
			input.useDelimiter("\\|");
			
			while (input.hasNext()) {
				appName = input.next().trim();
				if (input.hasNextInt()) {
					itemID = Integer.toString(input.nextInt());
					if (input.hasNextDouble()) {
						price = Double.toString(input.nextDouble());
						result.add(itemID + " " + appName + spaces(LINE_SIZE - itemID.length() - appName.length() - price.length() - 2) + "$" + price);
					}
				}
			}
			
		} catch (IOException e) {
			return new ArrayList<String>();
		} finally {
			if (myStream != null) {
				try {
					myStream.close();
				} catch (IOException e) {
					
				}
			}
		}
		
		return result;
	}
	
	public static boolean SavePayment(String user, String firstName, String lastName, String cardNumber, String month, String year, String street, String city, String state, String zip) {
		boolean isSuccess;
		
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("login_ID", user));
		params.add(new BasicNameValuePair("first_name", firstName));
		params.add(new BasicNameValuePair("last_name", lastName));
		params.add(new BasicNameValuePair("card_number", cardNumber));
		params.add(new BasicNameValuePair("expiration_month", month));
		params.add(new BasicNameValuePair("expiration_year", year));
		params.add(new BasicNameValuePair("street", street));
		params.add(new BasicNameValuePair("city", city));
		params.add(new BasicNameValuePair("state", state));
		params.add(new BasicNameValuePair("zip", zip));
		
		isSuccess = sendPost(INSERT_PAYMENT_URL, params);
		
		return isSuccess;
	}
	
	public static boolean SavePurchase(String user, String itemID) {
		boolean isSuccess;
		
		ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("login_ID", user));
		params.add(new BasicNameValuePair("item_ID", itemID));
		
		isSuccess = sendPost(INSERT_PURCHASE_URL, params);
		
		return isSuccess;
	}
	
	private static InputStream getStream(String myurl) throws IOException {
		URL url = new URL(myurl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setReadTimeout(10000 /* milliseconds */);
		conn.setConnectTimeout(15000 /* milliseconds */);
		conn.setRequestMethod("GET");
		conn.setDoInput(true);
		
		conn.connect();
		//Log.d(DEBUG_TAG, "The response is: " + conn.getResponseCode());

		return conn.getInputStream();
	}
	
	private static boolean sendPost(String myurl, ArrayList<NameValuePair> params) {
		InputStream myStream = null;
		Scanner input;
		boolean isSuccess = false;
		String result;
		
		try {
			myStream = postStream(myurl, params);
			
			input = new Scanner(myStream);
			if (input.hasNext()) {
				result = input.next().trim();
				if(result.equals("success")) {
					isSuccess = true;
				}
			};
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (myStream != null) {
				try {
					myStream.close();
				} catch (IOException e) {
					
				}
			}
		}
		
		return isSuccess;
	}
	
	private static InputStream postStream(String myurl, ArrayList<NameValuePair> params) throws IOException {
		URL url = new URL(myurl);
		HttpURLConnection conn = (HttpURLConnection) url.openConnection();
		conn.setReadTimeout(10000);
		conn.setConnectTimeout(15000);
		conn.setRequestMethod("POST");
		conn.setDoInput(true);
		conn.setDoOutput(true);

		OutputStream os = conn.getOutputStream();
		BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
		writer.write(getQuery(params));
		writer.close();
		os.close();

		conn.connect();
		Log.d("POST", "The response is: " + conn.getResponseCode());
		
		return conn.getInputStream();
	}
	
	private static String getQuery(ArrayList<NameValuePair> params) throws UnsupportedEncodingException {
	    StringBuilder result = new StringBuilder();
	    boolean first = true;
	    
	    for (NameValuePair pair : params)
	    {
	        if (first)
	            first = false;
	        else
	            result.append("&");
	        
	        result.append(URLEncoder.encode(pair.getName(), "UTF-8"));
	        result.append("=");
	        result.append(URLEncoder.encode(pair.getValue(), "UTF-8"));
	    }
	    
	    return result.toString();
	}
	
	// convert InputStream to String
	private static String getStringFromInputStream(InputStream is) {
		
		BufferedReader br = null;
		StringBuilder sb = new StringBuilder();
		
		String line;
		try {
			
			br = new BufferedReader(new InputStreamReader(is));
			while ((line = br.readLine()) != null) {
				sb.append(line);
			}
			
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		return sb.toString();
		
	}
}
